{% extends "admin/layout.html" %}

{% block title %}同步日志 - {{ system_config.site_name|default('项目管理系统') }}{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 页面标题和操作按钮 -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div class="d-flex align-items-center">
            <div class="me-3">
                <i class="fas fa-sync-alt fa-2x text-primary"></i>
            </div>
            <div>
                <h2 class="fw-bold mb-1">企业微信同步日志</h2>
                <p class="text-muted mb-0">查看组织架构与人员信息的同步记录</p>
            </div>
        </div>
        <button class="btn btn-primary d-flex align-items-center" id="manualSyncBtn">
            <i class="fas fa-sync me-2"></i>手动同步
        </button>
    </div>

    <!-- 统计卡片 -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card stat-card h-100">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-start">
                        <div>
                            <h6 class="card-title text-muted mb-2">总同步次数</h6>
                            <h3 class="fw-bold text-primary">{{ total_count }}</h3>
                        </div>
                        <div class="bg-primary bg-opacity-10 p-3 rounded">
                            <i class="fas fa-history text-primary"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card stat-card h-100">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-start">
                        <div>
                            <h6 class="card-title text-muted mb-2">成功次数</h6>
                            <h3 class="fw-bold text-success">{{ success_count }}</h3>
                        </div>
                        <div class="bg-success bg-opacity-10 p-3 rounded">
                            <i class="fas fa-check-circle text-success"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card stat-card h-100">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-start">
                        <div>
                            <h6 class="card-title text-muted mb-2">失败次数</h6>
                            <h3 class="fw-bold text-danger">{{ failed_count }}</h3>
                        </div>
                        <div class="bg-danger bg-opacity-10 p-3 rounded">
                            <i class="fas fa-times-circle text-danger"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card stat-card h-100">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-start">
                        <div>
                            <h6 class="card-title text-muted mb-2">最近同步</h6>
                            <h6 class="fw-bold text-info">
                                {% if recent_sync %}
                                    {{ recent_sync.strftime('%m-%d %H:%M') }}
                                {% else %}
                                    暂无记录
                                {% endif %}
                            </h6>
                        </div>
                        <div class="bg-info bg-opacity-10 p-3 rounded">
                            <i class="fas fa-clock text-info"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 筛选区域 -->
    <div class="card mb-4">
        <div class="card-body">
            <div class="row g-3">
                <div class="col-md-3">
                    <label class="form-label fw-semibold">开始日期</label>
                    <input type="date" class="form-control" id="startDate">
                </div>
                <div class="col-md-3">
                    <label class="form-label fw-semibold">结束日期</label>
                    <input type="date" class="form-control" id="endDate">
                </div>
                <div class="col-md-2">
                    <label class="form-label fw-semibold">同步状态</label>
                    <select class="form-select" id="statusFilter">
                        <option value="">全部状态</option>
                        <option value="success">成功</option>
                        <option value="processing">进行中</option>
                        <option value="failure">失败</option>
                    </select>
                </div>
                <div class="col-md-4 d-flex align-items-end">
                    <div class="d-flex gap-2 w-100">
                        <button class="btn btn-primary flex-fill d-flex align-items-center justify-content-center" id="filterBtn">
                            <i class="fas fa-filter me-2"></i>筛选
                        </button>
                        <button class="btn btn-outline-secondary d-flex align-items-center justify-content-center" id="resetFilter">
                            <i class="fas fa-redo me-2"></i>重置
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 日志列表 -->
    <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="card-title mb-0 fw-semibold">
                <i class="fas fa-list-check me-2"></i>同步记录
            </h5>
            <div class="d-flex align-items-center">
                <div class="input-group input-group-sm me-2" style="width: 250px;">
                    <span class="input-group-text bg-white">
                        <i class="fas fa-search text-muted"></i>
                    </span>
                    <input type="text" class="form-control border-start-0" placeholder="搜索日志..." id="logSearch">
                </div>
                <button class="btn btn-sm btn-outline-secondary" id="exportBtn">
                    <i class="fas fa-download me-1"></i>导出
                </button>
            </div>
        </div>

        <div class="card-body p-0">
            {% if logs|length == 0 %}
            <div class="text-center py-5">
                <div class="mb-4">
                    <i class="fas fa-inbox fa-4x text-muted"></i>
                </div>
                <h4 class="text-muted mb-2">暂无同步记录</h4>
                <p class="text-muted mb-4">尚未执行过同步操作，点击上方按钮进行手动同步</p>
                <button class="btn btn-primary" id="emptyStateSyncBtn">
                    <i class="fas fa-sync me-2"></i>立即同步
                </button>
            </div>
            {% else %}
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead class="table-light">
                        <tr>
                            <th width="15%">同步时间</th>
                            <th width="10%">状态</th>
                            <th width="12%">新增部门</th>
                            <th width="12%">更新部门</th>
                            <th width="12%">新增用户</th>
                            <th width="12%">更新用户</th>
                            <th width="27%">操作详情</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for log in logs %}
                        <tr class="align-middle">
                            <td>
                                <div class="d-flex align-items-center">
                                    <div class="me-2">
                                        <i class="far fa-clock text-muted"></i>
                                    </div>
                                    <div>
                                        <div class="fw-semibold">{{ log.sync_time.strftime('%Y-%m-%d') }}</div>
                                        <small class="text-muted">{{ log.sync_time.strftime('%H:%M:%S') }}</small>
                                    </div>
                                </div>
                            </td>
                            <td>
                                {% if log.status == 'success' %}
                                <span class="badge bg-success">成功</span>
                                {% elif log.status == 'processing' %}
                                <span class="badge bg-warning">进行中</span>
                                {% else %}
                                <span class="badge bg-danger">失败</span>
                                {% endif %}
                            </td>
                            <td>
                                <div class="d-flex align-items-center">
                                    <i class="fas fa-plus text-success me-2"></i>
                                    <span class="fw-bold {% if log.departments_added > 0 %}text-success{% else %}text-muted{% endif %}">
                                        {{ log.departments_added }}
                                    </span>
                                </div>
                            </td>
                            <td>
                                <div class="d-flex align-items-center">
                                    <i class="fas fa-pen text-primary me-2"></i>
                                    <span class="fw-bold {% if log.departments_updated > 0 %}text-primary{% else %}text-muted{% endif %}">
                                        {{ log.departments_updated }}
                                    </span>
                                </div>
                            </td>
                            <td>
                                <div class="d-flex align-items-center">
                                    <i class="fas fa-user-plus text-success me-2"></i>
                                    <span class="fw-bold {% if log.users_added > 0 %}text-success{% else %}text-muted{% endif %}">
                                        {{ log.users_added }}
                                    </span>
                                </div>
                            </td>
                            <td>
                                <div class="d-flex align-items-center">
                                    <i class="fas fa-user-pen text-primary me-2"></i>
                                    <span class="fw-bold {% if log.users_updated > 0 %}text-primary{% else %}text-muted{% endif %}">
                                        {{ log.users_updated }}
                                    </span>
                                </div>
                            </td>
                            <td>
                                <div class="d-flex align-items-center">
                                    <button class="btn btn-sm btn-outline-primary rounded-pill me-2"
                                            data-bs-toggle="collapse"
                                            data-bs-target="#logDetail{{ loop.index }}">
                                        <i class="fas fa-chevron-down me-1"></i>详情
                                    </button>
                                    <span class="text-truncate" style="max-width: 200px;" title="{{ log.message }}">
                                        {{ log.message }}
                                    </span>
                                </div>
                                <div class="collapse mt-2" id="logDetail{{ loop.index }}">
                                    <div class="card card-body bg-light">
                                        <div class="d-flex align-items-center mb-2">
                                            <i class="fas fa-info-circle text-primary me-2"></i>
                                            <h6 class="mb-0">同步详情</h6>
                                        </div>
                                        <div class="bg-white p-3 rounded border">
                                            <pre class="mb-0" style="white-space: pre-wrap; font-size: 0.875rem;">{{ log.message }}</pre>
                                        </div>
                                    </div>
                                </div>
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
            {% endif %}
        </div>

        {% if logs|length > 0 %}
        <div class="card-footer d-flex justify-content-between align-items-center">
            <div class="text-muted">
                <i class="fas fa-database me-1"></i>
                共 <span class="fw-bold">{{ pagination.total }}</span> 条记录
            </div>
            <nav>
                <ul class="pagination pagination-sm mb-0">
                    <li class="page-item {% if not pagination.has_prev %}disabled{% endif %}">
                        <a class="page-link" href="{{ url_for('wxwork.sync_logs', page=pagination.prev_num) if pagination.has_prev else '#' }}" tabindex="-1">
                            <i class="fas fa-chevron-left"></i>
                        </a>
                    </li>

                    {% for page_num in pagination.iter_pages(left_edge=1, right_edge=1, left_current=2, right_current=3) %}
                        {% if page_num %}
                            <li class="page-item {% if page_num == pagination.page %}active{% endif %}">
                                <a class="page-link" href="{{ url_for('wxwork.sync_logs', page=page_num) }}">
                                    {{ page_num }}
                                </a>
                            </li>
                        {% else %}
                            <li class="page-item disabled">
                                <span class="page-link">...</span>
                            </li>
                        {% endif %}
                    {% endfor %}

                    <li class="page-item {% if not pagination.has_next %}disabled{% endif %}">
                        <a class="page-link" href="{{ url_for('wxwork.sync_logs', page=pagination.next_num) if pagination.has_next else '#' }}">
                            <i class="fas fa-chevron-right"></i>
                        </a>
                    </li>
                </ul>
            </nav>
        </div>
        {% endif %}
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // 初始化日期选择器（不设置默认值）
    const urlParams = new URLSearchParams(window.location.search);
    if(urlParams.has('start')) {
        document.getElementById('startDate').value = urlParams.get('start');
    }
    if(urlParams.has('end')) {
        document.getElementById('endDate').value = urlParams.get('end');
    }
    if(urlParams.has('status')) {
        document.getElementById('statusFilter').value = urlParams.get('status');
    }

    // 手动同步按钮事件
    function handleManualSync(btn) {
        const originalText = btn.innerHTML;
        btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>同步中...';
        btn.disabled = true;

        fetch('{{ url_for("wxwork.sync_organization") }}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': '{{ csrf_token() }}'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const toast = new bootstrap.Toast(document.getElementById('operationToast'));
                document.getElementById('toastBody').textContent = '同步请求已发送，页面即将刷新';
                document.getElementById('toastIcon').className = 'fas fa-check-circle me-2 text-success';
                toast.show();
                setTimeout(() => location.reload(), 2000);
            } else {
                const toast = new bootstrap.Toast(document.getElementById('operationToast'));
                document.getElementById('toastBody').textContent = '同步失败: ' + data.message;
                document.getElementById('toastIcon').className = 'fas fa-exclamation-circle me-2 text-danger';
                toast.show();
                btn.innerHTML = originalText;
                btn.disabled = false;
            }
        })
        .catch(error => {
            console.error('Error:', error);
            const toast = new bootstrap.Toast(document.getElementById('operationToast'));
            document.getElementById('toastBody').textContent = '请求失败，请检查网络连接';
            document.getElementById('toastIcon').className = 'fas fa-exclamation-circle me-2 text-danger';
            toast.show();
            btn.innerHTML = originalText;
            btn.disabled = false;
        });
    }

    // 绑定手动同步按钮事件
    document.getElementById('manualSyncBtn').addEventListener('click', function() {
        handleManualSync(this);
    });

    // 绑定空状态同步按钮事件
    document.getElementById('emptyStateSyncBtn')?.addEventListener('click', function() {
        handleManualSync(document.getElementById('manualSyncBtn'));
    });

    // 筛选按钮事件
    document.getElementById('filterBtn').addEventListener('click', function() {
        const start = document.getElementById('startDate').value;
        const end = document.getElementById('endDate').value;
        const status = document.getElementById('statusFilter').value;

        let url = '{{ url_for("wxwork.sync_logs") }}?';
        const params = [];

        if (start) params.push(`start=${start}`);
        if (end) params.push(`end=${end}`);
        if (status) params.push(`status=${status}`);

        window.location.href = url + params.join('&');
    });

    // 重置按钮事件
    document.getElementById('resetFilter').addEventListener('click', function() {
        window.location.href = '{{ url_for("wxwork.sync_logs") }}';
    });

    // 搜索功能
    document.getElementById('logSearch').addEventListener('input', function() {
        const searchText = this.value.toLowerCase();
        const rows = document.querySelectorAll('tbody tr');

        rows.forEach(row => {
            const text = row.textContent.toLowerCase();
            row.style.display = text.includes(searchText) ? '' : 'none';
        });
    });

    // 导出功能
    document.getElementById('exportBtn').addEventListener('click', function() {
        const toast = new bootstrap.Toast(document.getElementById('operationToast'));
        document.getElementById('toastBody').textContent = '导出功能开发中，敬请期待';
        document.getElementById('toastIcon').className = 'fas fa-info-circle me-2 text-info';
        toast.show();
    });
});
</script>
{% endblock %}